package com.cosytek.farmmanager.data;

import com.cosytek.farmmanager.MsgManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
* Created by Happy on 2015/4/19.
        */
public class Main {
    private ArrayList<Farm> farms;

    private ArrayList<FarmSummary> farmSummaries;

    private Main() {}

    public static Main createFromJSONObject(JSONObject jsonObject) {
        Main main = new Main();
        if (main.refreshFromJSONObject(jsonObject)) {
            return main;
        }

        return null;
    }

    public boolean refreshFromJSONObject(JSONObject jsonObject) {
        try {
            farmSummaries = new ArrayList<FarmSummary>();
            JSONArray jfa = jsonObject.getJSONArray("farms");
            for (int i = 0; i < jfa.length(); i++) {
                JSONObject jf = jfa.getJSONObject(i);

                FarmSummary fs = FarmSummary.createFromJSONObject(jf);
                if (fs != null) {
                    farmSummaries.add(fs);
                }
            }

            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    public int getFarmSummaryCount() {
        return farmSummaries.size();
    }

    public FarmSummary getFarmSummary(int position) {
        return farmSummaries.get(position);
    }

    public Farm getFarm(String farmId) {
        if (farms == null) {
            return null;
        }

        for(Farm f: farms) {
            if (f.getId().equals(farmId)) {
                return f;
            }
        }
        return null;
    }

    public Farm onFarmLoaded(String respBody) {
        try {
            JSONObject jf = new JSONObject(respBody);
            String id = jf.getString("id");

            if (farms == null) {
                farms = new ArrayList<Farm>();
            }

            for(Farm f:farms) {
                if (f.getId().equals(id)) {
                    f.refreshFromJSONObject(jf);
                    return f;
                }
            }

            Farm f = Farm.createFromJSONObject(jf);
            farms.add(f);

            return f;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}
